package ui;

import logic.IMessageHandler;
import logic.ServerMessageHandler;
import logic.UserMessageHandler;
import network.message.MessageConstants;
import network.server.SocketServerProvider;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: grigory.rozhkov
 * Date: 15.09.12
 * Time: 0:31
 * To change this template use File | Settings | File Templates.
 */
public class MainPanel extends JPanel {
    private JTextField query;
    private JTextArea result;

    public MainPanel (int width, int height) {
        this.setBackground(Color.WHITE);
        this.setLayout(null);
        this.setSize(width, height);

        Font newFont = new Font(this.getFont().getName(), Font.BOLD, Math.min(height / 20, width / 20));

        JLabel newQuery = new JLabel("TYPE YOUR QUERY HERE:");
        newQuery.setBounds(0, 0, width, height / 5);
        newQuery.setFont(newFont);
        this.add(newQuery);

        query = new JTextField("");
        query.setBounds(0, height / 5, width, height / 5);
        query.setFont(newFont);
        this.add(query);

        JButton sendQuery = new JButton("SEND QUERY");
        sendQuery.setBounds(0, height * 2 / 5, width, height / 5);
        sendQuery.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                sendQueryToServer();
            }
        });
        this.add(sendQuery);

        result = new JTextArea();
        result.setBounds(0, height * 3 / 5, width, height * 2 / 5);
        result.setFont(newFont);
        result.setEditable(false);
        this.add(result);
    }

    private void sendQueryToServer() {
        result.setText("");
        String userMessage = query.getText();

        IMessageHandler userMessageHandler = new UserMessageHandler();
        IMessageHandler serverMessageHandler = new ServerMessageHandler();

        String userHandledMessage = userMessageHandler.handleMessage(userMessage);
        if (MessageConstants.FAIL.equals(userHandledMessage)) {
            result.setText(MessageConstants.FAILURE_WRONG_MESSAGE);
            return;
        }

        SocketServerProvider socketServerProvider = new SocketServerProvider();
        try {
            String serverResponse = socketServerProvider.sendMessage(userHandledMessage);
            String handledServerResponse = serverMessageHandler.handleMessage(serverResponse);
            result.setText(handledServerResponse);
            query.setText("");
        } catch (IOException e) {
            result.setText(MessageConstants.PROBLEM_WITH_SERVER);
            query.setText("");
        }
    }
}
